package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityBiddingCargoPublishCostBinding;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.utils.CustomTextWatcher;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.PickerHelper;
import com.sgb.kjwl.utils.RangeFocusChangeListener;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.viewmodel.transport.BiddingCargoPublishCostViewModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MToast;

import java.util.List;

/**
 * @author: 杨畔
 * @date: 2020/12/29 17:50
 * @Description: 竞价货源发布填写费用信息页面
 */
public class BiddingCargoPublishCostActivity extends AppActivity {
    BiddingCargoPublishCostViewModel viewModel;
    ActivityBiddingCargoPublishCostBinding binding;
    //选择弹窗
    private OptionsPickerView<GoodsInfoTypeEntity3> mPayPicker;
    private OptionsPickerView<GoodsInfoTypeEntity3> mTaxPicker;
    //数据实体类
    private CargoPublishEntity mEntity;

    public static void start(Activity activity, CargoPublishEntity entity, int requestCode) {
        Intent intent = new Intent(activity, BiddingCargoPublishCostActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(RouterKey.DATA, entity);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        viewModel = new ViewModelProvider(this).get(BiddingCargoPublishCostViewModel.class);
    }

    @Override
    protected void init() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_bidding_cargo_publish_cost);
        binding.setLifecycleOwner(this);
        binding.includeTitle.titleView.setText("费用要求");
        initEvent();
        initData();
    }

    private void initEvent() {
        binding.setOnClick(this);
        binding.includeTitle.ivBack.setOnClickListener(this);
        //设置输入范围，失去焦点后自动补全
        binding.etReleaseCargoFreight.setOnFocusChangeListener(new RangeFocusChangeListener(1, 50000));
        binding.etReleaseCargoDamageAgreement.setOnFocusChangeListener(new RangeFocusChangeListener(1, 50000));
        binding.etReleaseCargoDamageCompensation.setOnFocusChangeListener(new RangeFocusChangeListener(1, 50000));
        //监听运费
        binding.etReleaseCargoFreight.addTextChangedListener(new CustomTextWatcher() {
            @Override
            protected void delayedChanged(Editable content) {
                //设置运费
                mEntity.setFreight(NumberUtil.convertToDouble(content.toString()));
                adjustFreight();
            }
        });
        //接口回调
        viewModel.ldPay.observe(this, this::syncPayType);
        viewModel.ldTax.observe(this, this::syncTaxPicker);
    }

    private void initData() {
        mEntity = getIntent().getParcelableExtra(RouterKey.DATA);
        if (mEntity == null) {
            mEntity = new CargoPublishEntity();
        }
        //默认选中元/吨
        if (mEntity.getFreightMode() == 0) {
            switchFreightMode(0);
        } else {
            syncData();
        }
        //
        viewModel.getPayType();
        viewModel.getTax();
    }

    private void syncData() {
        if (mEntity.getFreight() != 0) {
            binding.etReleaseCargoFreight.setText(NumberUtil.trim0(mEntity.getFreight()));
        }
        switch (mEntity.getFreightMode()) {
            case CargoPublishEntity.FreightMode.MODE_WEIGHT://吨
                switchFreightMode(0);
                break;
            case CargoPublishEntity.FreightMode.MODE_VOLUME://方
                switchFreightMode(1);
                break;
        }
        //付款方式、是否含税、货损约定、货损赔偿、其他结算要求
        if (!TextUtils.isEmpty(mEntity.getPayType())) {
            binding.tvReleaseCargoPayWay.setText(mEntity.getPayType());
        }
        if (mEntity.getIncludeTax() != null) {
            binding.tvReleaseCargoTax.setText(mEntity.getIncludeTax() ? "含税" : "不含税");
        }
        if (mEntity.getDamageAgreement() != null) {
            binding.etReleaseCargoDamageAgreement.setText(NumberUtil.trim0(mEntity.getDamageAgreement()));
        }
        if (mEntity.getDamageCompensation() != null) {
            binding.etReleaseCargoDamageCompensation.setText(NumberUtil.trim0(mEntity.getDamageCompensation()));
        }
        if (!TextUtils.isEmpty(mEntity.getOtherSettlementReq())) {
            binding.etReleaseCargoOtherSettlementRequirements.setText(mEntity.getOtherSettlementReq());
        }
    }

    /**
     * 设置付款方式
     */
    private void syncPayType(List<GoodsInfoTypeEntity3> list) {
        mPayPicker = PickerHelper.with(this).getCommonPicker("选择付款方式", list, (options1, options2, options3, v) -> {
            GoodsInfoTypeEntity3 entity = list.get(options1);
            //设置数据
            mEntity.setPayType(entity.getName());
            //设置回显
            binding.tvReleaseCargoPayWay.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    /**
     * 设置付款方式
     */
    private void syncTaxPicker(List<GoodsInfoTypeEntity3> list) {
        mTaxPicker = PickerHelper.with(this).getCommonPicker("选择是否含税", list, (options1, options2, options3, v) -> {
            GoodsInfoTypeEntity3 entity = list.get(options1);
            //设置数据
            mEntity.setIncludeTax("1".equals(entity.getNo()));
            //设置回显
            binding.tvReleaseCargoTax.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    @Override
    public void onClick(View v) {
        closeKeybord();
        if (v == binding.includeTitle.ivBack) {
            finish();
        } else if (v == binding.tvReleaseCargoWeight) {
            //防止重复点击
            if (binding.tvReleaseCargoWeight.isSelected()) {
                return;
            }
            //判断是否填写货重
            if (mEntity.getGoodsWeight() == 0) {
                MToast.showToast(this, "请先至货物信息中填写货重");
                return;
            }
            switchFreightMode(0);
        } else if (v == binding.tvReleaseCargoVolume) {
            //防止重复点击
            if (binding.tvReleaseCargoVolume.isSelected()) {
                return;
            }
            //判断是否填写体积
            if (mEntity.getGoodsVolume() == 0) {
                MToast.showToast(this, "请先至货物信息中填写货物体积");
                return;
            }
            switchFreightMode(1);
        } else if (v == binding.llReleaseCargoPayWay) {
            if (mPayPicker != null) {
                mPayPicker.show();
            }
        } else if (v == binding.llReleaseCargoTax) {
            if (mTaxPicker != null) {
                mTaxPicker.show();
            }
        } else if (v == binding.tvReleaseCargoSubmit) {
            clearAllFocus();
            checkData();
        }
    }

    /**
     * 切换运费方式
     */
    private void switchFreightMode(int position) {
        int count = binding.llReleaseCargoFreightType.getChildCount();
        for (int i = 0; i < count; i++) {
            binding.llReleaseCargoFreightType.getChildAt(i).setSelected(false);
        }
        binding.llReleaseCargoFreightType.getChildAt(position).setSelected(true);
        //设置运费方式
        switch (position) {
            case 0:
                mEntity.setFreightMode(CargoPublishEntity.FreightMode.MODE_WEIGHT);
                binding.tvReleaseCargoFreightSuffix.setText("元/吨");
                break;
            case 1:
                mEntity.setFreightMode(CargoPublishEntity.FreightMode.MODE_VOLUME);
                binding.tvReleaseCargoFreightSuffix.setText("元/方");
                break;
        }
        //重算总运费
        adjustFreight();
    }

    /**
     * 调整运费
     */
    private void adjustFreight() {
        if (mEntity.getFreight() == 0 || mEntity.getFreightMode() == 0) {
            binding.llReleaseCargoFreight.setVisibility(View.GONE);
            return;
        }
        binding.llReleaseCargoFreight.setVisibility(View.VISIBLE);
        //根据运费类型计算运费
        switch (mEntity.getFreightMode()) {
            case CargoPublishEntity.FreightMode.MODE_WEIGHT:
                binding.tvReleaseCargoFreightTotal.setText(String.format("%s元", NumberUtil.trim0(mEntity.getGoodsWeight() * mEntity.getFreight())));
                break;
            case CargoPublishEntity.FreightMode.MODE_VOLUME:
                binding.tvReleaseCargoFreightTotal.setText(String.format("%s元", NumberUtil.trim0(mEntity.getGoodsVolume() * mEntity.getFreight())));
                break;
        }
    }

    /**
     * 检查数据并回传
     */
    private void checkData() {
        if (mEntity == null) return;
        String freight = binding.etReleaseCargoFreight.getText().toString();
        if (TextUtils.isEmpty(freight)) {
            MToast.showToast(this, "请输入运费单价");
            return;
        }
        if (mEntity.getFreightMode() == 0) {
            MToast.showToast(this, "请选择价格单位");
            return;
        }
        if (TextUtils.isEmpty(mEntity.getPayType())) {
            MToast.showToast(this, "请选择付款方式");
            return;
        }
        //设置运费
        mEntity.setFreight(NumberUtil.convertToDouble(freight));
        //货损约定、货损赔偿、其他结算要求
        if (!TextUtils.isEmpty(binding.etReleaseCargoDamageAgreement.getText())) {
            mEntity.setDamageAgreement(NumberUtil.convertToDouble(binding.etReleaseCargoDamageAgreement.getText().toString()));
        } else {
            mEntity.setDamageAgreement(null);
        }
        if (!TextUtils.isEmpty(binding.etReleaseCargoDamageCompensation.getText())) {
            mEntity.setDamageCompensation(NumberUtil.convertToDouble(binding.etReleaseCargoDamageCompensation.getText().toString()));
        } else {
            mEntity.setDamageCompensation(null);
        }
        if (binding.etReleaseCargoOtherSettlementRequirements.getText() != null) {
            mEntity.setOtherSettlementReq(binding.etReleaseCargoOtherSettlementRequirements.getText().toString());
        } else {
            mEntity.setOtherSettlementReq(null);
        }
        //修改运费展示
        adjustFreight();
        Intent intent = new Intent();
        intent.putExtra(RouterKey.DATA, mEntity);
        setResult(RESULT_OK, intent);
        finish();
    }
}
